package org.NooLab.itexx.app.config;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.NooLab.itexx.ITexxWindowCommons;
import org.NooLab.itexx.app.controller.content.SearchEngine;
import org.NooLab.itexx.app.controller.content.SearchEngines;
import org.NooLab.utilities.inifile.IniStyleContent;
import org.NooLab.utilities.inifile.IniStyleSection;
import org.NooLab.utilities.inifile.IniStyleSections;
import org.NooLab.utilities.inifile.ItemValue;
import org.NooLab.utilities.strings.StringsUtil;



/**
 * 
 * this relates to the file "preferences.txt"
 * 
 * 
 *
 */
public class ITexxIniPreferences implements Serializable{

	private static final long serialVersionUID = -702967214611535061L;
	
	transient private ITexxWindowCommons appCommons;
	transient private ITexxAppProperties appProperties;
	
	IniStyleSections iniSections ;
	IniStyleContent inifile;
	
	int showresultsearly = 1;
	
	boolean blueButtons , smallButtons, buttonsOnTop;
	
	int panelsMinHeight = 45;
	int panelsMaxHeight = 250;
	int panelsDefaultHeight=120;
	
	int panelsMaxNumber=100;
	int showPanelEnumeration=0;
	
	String panelsFont = "Tahoma";
	int    panelsFontsize=11 ;

	ArrayList<String> excludedDomains = new ArrayList<String>();
		// such as twitter.com, youtube.com

	ArrayList<SearchEngineDefinition> engines = new ArrayList<SearchEngineDefinition>();

	int showSearchtextField;

	private boolean showLogoInSimpleView=true;

	private int alwaysOnTop=0;

	private int adaptiveVerticalSize=0;
	
	float maxPanelTransparancy = 0.99f;

	// process
	
	int showRawSer = 0;
	int showSerTitles = 0;

	
	// advanced
	private ArrayList<String> openNlpLanguages;
	transient String openNlpLanguageDescr;

	private int astorActivation=0, astorSource=1;
		  
	
	transient StringsUtil strgutil = new StringsUtil ();

	// ========================================================================
	public ITexxIniPreferences(ITexxAppProperties props) {
		
		appProperties = props;
	}
	// ========================================================================
	
	
	public void loadFromFile(String ppath) {
		// 
		/*
		 * most important: showing search text field, engines, height of panels
		 */
		
		
		try {
			if (strgutil ==null){
				strgutil = new StringsUtil ();  
			}
			
			inifile = new IniStyleContent(ppath);

			
			iniSections = inifile.getIniStyleSections() ;
			// [display],		 panels.defaultheight=75
			
			panelsDefaultHeight = iniSections.getEntryValue( "display","panels.defaultheight", panelsDefaultHeight );
								  if (panelsDefaultHeight>panelsMaxHeight)panelsDefaultHeight=panelsMaxHeight;
								  if (panelsDefaultHeight<panelsMinHeight)panelsDefaultHeight=panelsMinHeight;
			
			panelsMaxNumber = iniSections.getEntryValue( "display","panels.maxnumber", 50 );
			
			showresultsearly = iniSections.getEntryValue( "display","showresultsearly", 0 );
			
			
			panelsFont = iniSections.getEntryValue( "display","panels.font", "Tahoma" );
			
			panelsFontsize = iniSections.getEntryValue( "display","panels.fontsize", 12 );
			
			showSearchtextField = iniSections.getEntryValue( "display","searchtextfielddisplay", 0 );
			
			retrieveExcludedDomains( iniSections );
			 
			blueButtons  = iniSections.getEntryValue( "display","showbluebuttons", 0 )>0;
			smallButtons = iniSections.getEntryValue( "display","usesmallbuttons", 0 )>0;
			buttonsOnTop = iniSections.getEntryValue( "display","showbuttonsontop",0 )>0;
			
			showLogoInSimpleView = iniSections.getEntryValue( "display","showLogoInSimpleView",1 )>0;
			
			alwaysOnTop = iniSections.getEntryValue( "display","alwaysontop",0 );
			
			adaptiveVerticalSize = iniSections.getEntryValue( "display","adaptivesize",0 );
			
			
			maxPanelTransparancy = iniSections.getEntryValue( "display","panels.maxtransparancy", 1.0f );
			
			showPanelEnumeration = iniSections.getEntryValue( "display","panels.showenumeration",0 );
			
			// .......................................
			// [process]
			showRawSer = iniSections.getEntryValue( "process","searchengineresults.showimmediately",0 );
			
			showSerTitles = iniSections.getEntryValue( "process","searchengineresults.showtitles",1 );
			
			
			
			// .......................................
			// [advanced]  nlp.languages=de,en,pt,es
			openNlpLanguageDescr = iniSections.getEntryValue( "advanced","opennlp.languages", "en" );
							   openNlpLanguageDescr = strgutil.replaceAll(openNlpLanguageDescr, " ", ",");
							   openNlpLanguageDescr = strgutil.replaceAll(openNlpLanguageDescr, ";", ",");
							   openNlpLanguageDescr = strgutil.replaceAll(openNlpLanguageDescr, ",,", ",");
			openNlpLanguages = new ArrayList<String>(Arrays.asList( openNlpLanguageDescr.split(","))); 

			astorActivation = iniSections.getEntryValue( "advanced","astor", 0 );  // astor=0

			// ;sources to learn from: 1=only local, 2=only from dynamic retrievals of remote documents, 3=from both|||
			// ;note that 2 and 3 consume quite some processor capacity (take intel i5 as a minimum)|||
			astorSource =  iniSections.getEntryValue( "advanced","astor.source", 1 );  
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}


	private void retrieveExcludedDomains(IniStyleSections iniSections) {

		String domain;
		
		IniStyleSection section = iniSections.getByName("domains");
		
		excludedDomains.clear();
		ArrayList<String> entries = section.getEntries(); // return items like "exclude.1=facebook.com"
		
		for (int i=0;i<entries.size();i++){
			
			domain = iniSections.getEntryValue( "domains", "exclude."+(i+1), "" );
			if ((domain!=null) && (domain.length()>0)){
				// exclude.2=twitter.com|||
				excludedDomains.add(domain);
			}
		}
		
	}


	public void loadSearchEngineDefinitions( SearchEngines searchEngines) {
		// 
		ArrayList<IniStyleSection> sections;
		IniStyleSection sedSection ;
		ArrayList<String> entries ;
		Map<String, ItemValue> mappedEntries ;
		// ItemValue is a structured generic container for various primitive types
		String str;
		int vi;
		
		if (iniSections==null){
			iniSections = inifile.getIniStyleSections() ;
		}
		sections = iniSections.getByName("engine.",1) ;
		
		for (int i=0;i<sections.size();i++){
			
			SearchEngine se = searchEngines.getNewEngine(0);
			sedSection = sections.get(i);
			
			entries = sedSection.getEntries();
			mappedEntries = sedSection.getAllMappedEntries() ; 
			// mappedEntries = createSectionMap(entries) ;

			str = ((ItemValue)getMappedEntry( mappedEntries, "name", new ItemValue(""))).getValueStr();
			
			if ((str==null) || (str.length()==0)){
				continue;
			}
			se.setName( str );
			/*
			[engine.2]|||
			name=google|||
			address=http://www.google.com|||
			basicqueryurl=/search?num=10&hl=[?lang?]&newwindow=0&site=[?site?]&source=hp&q=[?q?]|||
			active=1|||
			indicator.maincontentarea=span.st|||
			indicator.resultitem=li.g|||
			indicator.resulttitle=h3.r|||
			indicator.resultcontentsnip=span.st|||
			; this could be facultative|||
			indicator.resultformat=span.[b w xsm]|||
			;|||
				
			*/			
			str = getMappedEntry( mappedEntries, "address", new ItemValue("")).getValueStr();
			se.setAddress( str );
			str = getMappedEntry( mappedEntries, "basicqueryurl", new ItemValue("")).getValueStr();

			se.setQueryUrlGenerator( str );
			
			ItemValue iiv = new ItemValue(0);
			vi  = getMappedEntry( mappedEntries, "active", iiv).getValueInt();
			se.setActive( vi>=1 );
			
			str = getMappedEntry( mappedEntries, "indicator.maincontentarea",new ItemValue("")).getValueStr();
			se.addIndicatorPattern("content", str );
			
			str = getMappedEntry( mappedEntries, "indicator.resultitem",new ItemValue("")).getValueStr();
			se.addIndicatorPattern("resultitem", str );
			
			str = getMappedEntry( mappedEntries, "indicator.resulttitle",new ItemValue("")).getValueStr();
			se.addIndicatorPattern("resulttitle", str );
			
			str = getMappedEntry( mappedEntries, "indicator.resultcontentsnip",new ItemValue("")).getValueStr();
			se.addIndicatorPattern("resultcontentsnip", str );
			
			str = getMappedEntry( mappedEntries, "indicator.resultformat",new ItemValue("")).getValueStr();
			se.addIndicatorPattern("resultformat", str ); // things like pdf, doc, ..
			
			searchEngines.getItems().add(se) ;
		}// i->
		
	}
	
	private ItemValue getMappedEntry(Map<String, ItemValue> mapE, String keystr, ItemValue defaultVal) {
		// 
		ItemValue obj=null;
		ItemValue value = null;
		
		obj = defaultVal;
		
		if (mapE.containsKey( keystr )){
			value = mapE.get( keystr );
		}
		
		
		if (value!=null){
			obj = value;
		}
		
		return obj;
	}


	private Map<String, ItemValue> createSectionMap(ArrayList<String> entries) {
		// 
		Map<String, ItemValue> map  = new HashMap<String, ItemValue>();
		String entry,part1,part2;
		String[] parts = new String[2] ;
		
		for (int i=0;i<entries.size();i++){
			
			entry = entries.get(i) ;
			part1=""; part2=""; parts[0]=""; parts[1]="";
			
			if (entry.contains("=")){
				parts = entry.split("=");
				if ((parts[1]!=null) && ((parts[1].length()>0))){
					map.put( parts[0], new ItemValue(parts[1]));
				} // ?
			}// ?
			
		} // i->
		
		return map;
	}
	

	public IniStyleSections getIniSections() {
		return iniSections;
	}


	public void setIniSections(IniStyleSections iniSections) {
		this.iniSections = iniSections;
	}


	public IniStyleContent getInifile() {
		return inifile;
	}


	public void setInifile(IniStyleContent inifile) {
		this.inifile = inifile;
	}


	public boolean isBlueButtons() {
		return blueButtons;
	}


	public void setBlueButtons(boolean blueButtons) {
		this.blueButtons = blueButtons;
	}


	public boolean isSmallButtons() {
		return smallButtons;
	}


	public void setSmallButtons(boolean smallButtons) {
		this.smallButtons = smallButtons;
	}


	public boolean isButtonsOnTop() {
		return buttonsOnTop;
	}


	public void setButtonsOnTop(boolean buttonsOnTop) {
		this.buttonsOnTop = buttonsOnTop;
	}


	public int getPanelsDefaultHeight() {
		return panelsDefaultHeight;
	}


	public void setPanelsDefaultHeight(int panelsDefaultHeight) {
		this.panelsDefaultHeight = panelsDefaultHeight;
	}


	public int getPanelsMaxNumber() {
		return panelsMaxNumber;
	}


	public void setPanelsMaxNumber(int panelsMaxNumber) {
		this.panelsMaxNumber = panelsMaxNumber;
	}


	public String getPanelsFont() {
		return panelsFont;
	}


	public void setPanelsFont(String panelsFont) {
		this.panelsFont = panelsFont;
	}


	public int getPanelsFontsize() {
		return panelsFontsize;
	}


	public void setPanelsFontsize(int panelsFontsize) {
		this.panelsFontsize = panelsFontsize;
	}


	public ArrayList<String> getExcludedDomains() {
		return excludedDomains;
	}


	public void setExcludedDomains(ArrayList<String> excludedDomains) {
		this.excludedDomains = excludedDomains;
	}


	public ArrayList<SearchEngineDefinition> getEngines() {
		return engines;
	}


	public void setEngines(ArrayList<SearchEngineDefinition> engines) {
		this.engines = engines;
	}


	public int getShowresultsearly() {
		return showresultsearly;
	}


	public void setShowresultsearly(int showresultsearly) {
		this.showresultsearly = showresultsearly;
	}


	public int getPanelsMinHeight() {
		return panelsMinHeight;
	}


	public void setPanelsMinHeight(int panelsMinHeight) {
		this.panelsMinHeight = panelsMinHeight;
	}


	public int getPanelsMaxHeight() {
		return panelsMaxHeight;
	}


	public void setPanelsMaxHeight(int panelsMaxHeight) {
		this.panelsMaxHeight = panelsMaxHeight;
	}


	public int getShowSearchtextField() {
		return showSearchtextField;
	}


	public void setShowSearchtextField(int showSearchtextField) {
		this.showSearchtextField = showSearchtextField;
	}


	public boolean isShowLogoInSimpleView() {
		//
		return showLogoInSimpleView;
	}


	public int getAlwaysOnTop() {
		// 
		return alwaysOnTop;
	}


	public int getAdaptiveVerticalSize() {
		return adaptiveVerticalSize;
	}


	public void setShowLogoInSimpleView(boolean showLogoInSimpleView) {
		this.showLogoInSimpleView = showLogoInSimpleView;
	}


	public void setAlwaysOnTop(int alwaysOnTop) {
		this.alwaysOnTop = alwaysOnTop;
	}


	public void setAdaptiveVerticalSize(int adaptiveVerticalSize) {
		this.adaptiveVerticalSize = adaptiveVerticalSize;
	}


	public float getMaxPanelTransparancy() {
		return maxPanelTransparancy;
	}


	public int getShowPanelEnumeration() {
		return showPanelEnumeration;
	}


	public void setShowPanelEnumeration(int showPanelEnumeration) {
		this.showPanelEnumeration = showPanelEnumeration;
	}


	public void setMaxPanelTransparancy(float maxPanelTransparancy) {
		this.maxPanelTransparancy = maxPanelTransparancy;
	}


	public ArrayList<String> getOpenNlpLanguages() {
		return openNlpLanguages;
	}


	public void setOpenNlpLanguages(ArrayList<String> languages) {
		this.openNlpLanguages = new ArrayList<String>(languages);
	}


	public int getAstorActivation() {
		return astorActivation;
	}


	public void setAstorActivation(int astorActivation) {
		this.astorActivation = astorActivation;
	}


	public int getAstorSource() {
		return astorSource;
	}


	public void setAstorSource(int astorSource) {
		this.astorSource = astorSource;
	}


	public int getShowRawSer() {
		// TODO Auto-generated method stub
		return showRawSer;
	}


	public int getShowSerTitles() {
		return showSerTitles;
	}


	public void setShowSerTitles(int showSerTitles) {
		this.showSerTitles = showSerTitles;
	}


	public void setShowRawSer(int showRawSer) {
		this.showRawSer = showRawSer;
	}


}

/*
;
[version]
version=1.0
;
[display]

;
showbluebuttons=0
usesmallbuttons=0
showbuttonsontop=0

panels.defaultheight=75
panels.maxnumber=40
; max = 100
; = commentary

panels.font=Tahoma
panels.fontsize=11

[domains]
exclude.1=facebook.com
exclude.2=twitter.com
exclude.3=youtube.com
exclude.4=answer.com
exclude.5=www.gutefrage
;
[engineresults]
;
initialnumber=50
; max = 1000 ; large number may take a long time to process!
;
;
[engine.1]
name=bing
address=http://www.bing.com
basicqueryurl=http://www.bing.com/search?q=[???]&go=&qs=ds&form=QBLH&filt=all
active=0
indicator.maincontentarea=
indicator.resultitem=
;
[engine.2]
name=google
address=http://www.bing.com
basicqueryurl=/search?num=10&hl=de&newwindow=1&site=&source=hp&q=[???]
active=1
indicator.maincontentarea=
indicator.resultitem=
indicator.removal.1=
indicator.removal.2=
;

[identifier.1]
name=wiki
configfile=
;

[identifier.2]
name=joomla
configfile=
;
[identifier.3]
name=wordpress
configfile=
;
[identifier.4]
name=drupal
configfile=
;
[identifier.5]
name=typo3
configfile=
;
[identifier.6]
name=generic
configfile=
;



*/